<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * date: 2020-10-20 10:37:46
 * @LastEditors: Sam
 * @LastEditTime: 2021-12-04 15:34:43
 */


namespace app\api\middleware;
use think\facade\Db;
use app\admin\model\User;
use app\Request;
use think\facade\Env;

/**
 * API接口token验证中间件
 * Class AuthTokenMiddleware
 * @package app\http\middleware
 */
class TokenMiddleware 
{
    public function handle(Request $request, \Closure $next, bool $force = true)
    {
        $authInfo = null;
        $token    = trim($request->header('token'));
        $jwt = \Jwt::getInstance();
        $jwt->setKey(Env::get('TOKEN_KEY')); //设置秘钥 每个项目务必更换
        $jwt->setIss(Env::get('TOKEN_ISS'));  //签发者  可以写项目名或者开发者姓名
        $info= $jwt->verifyToken($token);
        if(!$info) return json(['code'=>-1,'msg'=>'token验证失败，请重新登录']);
        $uid = $info['claim']['uid'];
        try {
            $authInfo = Db::name('user')->where('id',$uid)->find();
        } catch (AuthException $e) {
            if ($force)
                return json(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
        }
      
        if (!is_null($authInfo)) {
            Request::macro('user', function () use (&$authInfo) {
                return $authInfo;
            });
        }
        Request::macro('tokenData', function () use (&$info) {
            return $info;
        });
        Request::macro('isLogin', function () use (&$authInfo) {
            return !is_null($authInfo);
        });
        Request::macro('uid', function () use (&$authInfo) {
            return is_null($authInfo) ? 0 : $authInfo['id'];
        });

        return $next($request);
    }
}